package com.tuanzi.loan.web.bean.system.workflow;

import static com.tuanzi.loan.business.constants.DictionaryCode.WORKFLOW_CATEGORY;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.system.ProcessInstanceSearchRequest;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.system.WorkflowProcessInstanceLazyDataModel;
import com.tuanzi.loan.workflow.service.WorkflowProcessorService;
import com.tuanzi.loan.workflow.vo.ProcessInstanceResponse;
import com.tuanzi.loan.workflow.vo.TrackingResponse;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @author Ray 2017/09/22
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class WorkflowInstanceBean extends JSFListingBean<ProcessInstanceSearchRequest, ProcessInstanceResponse> {

	private static final long serialVersionUID = -2152778554108785342L;

	@Autowired
	private WorkflowProcessorService workflowProcessorService;

	private List<TrackingResponse> trackingResponses;
	private String procInstId;

	@PostConstruct
	private void init() {
		initLazyDataModel();
	}

	public void onReset() {
		initLazyDataModel();
	}

	private void initLazyDataModel() {
		$ = new ProcessInstanceSearchRequest();
		lazyDataModel = new WorkflowProcessInstanceLazyDataModel($);
	}

	public void onLoadProcessTracking(String procInstId) throws IOException {
		trackingResponses = workflowProcessorService.findProcessTrackingByProcInstId(procInstId);
	}

	public void onEndProcess(String procInstId) {
		workflowProcessorService.endProcess(procInstId);
	}

	public void suspendProcess(String procInstId) {
		workflowProcessorService.suspendProcess(procInstId);
	}

	public void activateProcess(String procInstId) {
		workflowProcessorService.activateProcess(procInstId);
	}

	public void redoProcess(String procInstId) {

	}

	private List<String> getSelectedProcDefIds() {
		return selectedRecords.parallelStream().map(ProcessInstanceResponse::getId).collect(Collectors.toList());
	}

	@Override
	protected List<String> getDictionaryCodes() {
		return Lists.newArrayList(WORKFLOW_CATEGORY);
	}
}
